<template>
	<view class="main">

		<!-- 顶部自定义导航 -->
		<!-- <minitemtag></minitemtag> -->
		<!-- 顶部选项卡 -->
		<view class="tab-frame">
			<scroll-view id="nav-bar" class="nav-bar" scroll-x scroll-with-animation :scroll-left="scrollLeft">
				<view v-for="(item,index) in tabBars" :key="item.channelId" class="nav-item" :class="{current: index === tabCurrentIndex}"
				 :id="'tab'+index" @click="changeTab(index,item.channelId)">{{item.channelName}}</view>
			</scroll-view>
			<view class="nab-icon" @click="listChannel=true">
				<u-icon class="icon" name="list" color="#bcbcbc" size="50"></u-icon>
			</view>
		</view>
		<!-- 列表频道 -->
		<u-popup closeable v-model="listChannel" mode="bottom" length="90%" border-radius="30">
			<view class="channelTxt">
				<!-- {{tabBars[0].showdel==false?'编辑':'完成'}} -->
				<view>所有频道<text>点击进入频道</text>
					<view v-show="editcomplete==false" @click="editcompleteClick(0)" class="edit">编辑</view>
					<view v-show="editcomplete==true" @click="editcompleteClick(1)" class="edit">完成</view>
				</view>
			</view>
			<view class="channelTag">
				<view class="tag-info" v-for="(item,index) in tabBars" :key="item.channelId">
					<u-tag @click="changeTab(index,item.channelId)" type="info" shape="circle" :text="item.channelName" :closeable="item.showdel"
					 @close="tagClick(index)" />
				</view>
			</view>
		</u-popup>
		<!-- 下拉刷新组件 -->
		<mix-pulldown-refresh ref="mixPulldownRefresh" class="panel-content" :top="235" @refresh="onPulldownReresh"
		 @setEnableScroll="setEnableScroll">
			<!-- 内容部分 -->
			<swiper id="swiper" class="swiper-box" :duration="300" :current="tabCurrentIndex" @change="changeTab">
				<swiper-item v-for="tabItem in tabBars" :key="tabItem.id">
					<scroll-view class="panel-scroll-box" :scroll-y="enableScroll" @scrolltolower="loadMore">
						<!-- 
							* 直播列表 
							* 和nvue的区别只是需要把uni标签转为weex标签而已
							* class 和 style的绑定限制了一些语法，其他并没有不同  @click="navToDetails(item.news_id)"
						-->
						<view v-for="(item, index) in tabItem.newsList" :key="index" class="video-frame" @click="watchClick()">
							<view class="video-content">
								<view class="frame_img">
									<image v-if="item.room_user.avatar_url" :src="item.room_user.avatar_url" mode=""></image>
									<image v-if="!item.room_user.avatar_url" src="https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1575568780,3963509117&fm=15&gp=0.jpg"
									 mode=""></image>
								</view>
								<view class="frame_tltle">
									<view>{{item.room_user.name}}</view>
									<text>{{item.room_user.fans_count}}粉丝</text>
								</view>
								<button @click="followClock(item)" style="padding: 10rpx 20rpx;" type="error" size="medium">{{item.follow===true?'已关注':'关注'}}</button>
							</view>
							<view class="frame-trxt"><text>{{item.room_name}}</text> {{item.room_describe}}</view>
							<view class="forame-image">
								<image :src="item.room_cover" mode=""></image>
								<view class="frame-watch">
									<view>直播中</view>
									<text>{{item.view_count}}人</text>
								</view>
							</view>
						</view>

						<!-- 上滑加载更多组件 -->
						<mix-load-more :status="tabItem.loadMoreStatus"></mix-load-more>
					</scroll-view>
				</swiper-item>
			</swiper>
		</mix-pulldown-refresh>
		<u-toast ref="uToast" />
	</view>

	</view>
</template>

<script>
	import utils from '@/components/shoyu-date/utils.filter.js';
	import mixAdvert from '@/components/mix-advert/vue/mix-advert';
	import mixPulldownRefresh from '@/components/mix-pulldown-refresh/mix-pulldown-refresh';
	import mixLoadMore from '@/components/mix-load-more/mix-load-more';
	let windowWidth = 0,
		scrollTimer = false,
		tabBar;
	export default {
		components: {
			mixPulldownRefresh,
			mixLoadMore,
			mixAdvert
		},
		data() {
			return {
				editcomplete: false, //编辑/完成
				listChannel: false, //底部侧频道列表展示
				utils: utils, //时间转换
				tabCurrentIndex: 0, //当前选项卡索引
				scrollLeft: 0, //顶部选项卡左滑距离
				enableScroll: true,
				tabBars: [],
				page_index: 1 //当前页数
			}
		},
		onShow() {
			// 获取屏幕宽度
			windowWidth = uni.getSystemInfoSync().windowWidth;
			this.loadTabbars();
		},

		methods: {
			//跳转详情页面
			watchClick(){ 
				uni.navigateTo({
					url: '/pages/livedetails/livedetails'/* :'/pages/livedetails/livedetails' */
				})
				/* 
				 uni.navigateTo({
				 	url: '/pages/article/article'
				 }); */
			},
			//关注
			async followClock(item) {

				if (item.follow == false) {
					const res = await this.$myRequest({
						url: '/user/follow',
						method: 'post',
						header: {},
						data: {
							up_uid: item.room_user.user_id
						}
					})
					this.$refs.uToast.show({
						title: '关注' + res.message,
						type: 'success'
					})
					item.follow = true
				} else {
					const res = await this.$myRequest({
						url: '/user/unfollow',
						method: 'post',
						header: {},
						data: {
							up_uid: item.room_user.user_id
						}
					})
					this.$refs.uToast.show({
						title: '取消关注' + res.message,
						type: 'success'
					})
					item.follow = false

				}
			},
			/**
			 * 数据处理方法在vue和nvue中通用，可以直接用mixin混合
			 * 这里直接写的，mixin使用方法看index.nuve
			 */
			//切换编辑完成
			editcompleteClick(type) {
				if (type == 0) {
					let tabList = this.tabBars;
					tabList.forEach(item => {
						item.showdel = true
					})
					this.tabBars = tabList;
				} else {
					let tabList = this.tabBars;
					tabList.forEach(item => {
						item.showdel = false
					})
					this.tabBars = tabList;
				}
				this.editcomplete = !this.editcomplete
			},
			//删除分类
			tagClick(index) {
				this.tabBars.splice(index, 1);
			},
			//获取分类
			async loadTabbars() {
				let datas = {}
				datas.lang_id = 1
				const res = await this.$myRequest({
					url: '/channel/get-channel-list',
					header: datas
				})
				let tabList = res.data.news_channel; //news_channel列表无数据，有数据后修改回来
				tabList.forEach(item => {
					item.showdel = false
					item.newsList = [];
					item.loadMoreStatus = 0; //加载更多 0加载前，1加载中，2没有更多了
					item.refreshing = 0; //动画
				})
				this.tabBars = tabList;
				this.loadNewsList('add');
			},
			//直播列表
			async loadNewsList(type) {
				let tabItem = this.tabBars[this.tabCurrentIndex];
				let channel_id = tabItem.channelId //频道id
				let page_size = 5 //每页显示多少条数据
				if (type === 'refresh') {
					tabItem.newsList = []; //刷新前清空数组
					this.page_index == 1
				}
				let page_index = this.page_index //当前第几页
				const res = await this.$myRequest({
					url: '/live/get-liveroom-list/' + channel_id + '/' + page_size + '/' + page_index,
					header: {}
				})
				//type add 加载更多 refresh下拉刷新
				if (type === 'add') {
					if (tabItem.loadMoreStatus === 2) {
						return;
					}
					tabItem.loadMoreStatus = 1;
				}
				// #ifdef APP-PLUS
				else if (type === 'refresh') {
					tabItem.refreshing = true;
				}
				// #endif

				//setTimeout模拟异步请求数据
				setTimeout(() => {
					/* let list = json.newsList; */
					let list = res.data;
					/* list.sort((a, b) => {
						return Math.random() > .5 ? -1 : 1; //静态数据打乱顺序
					}) */
					list.forEach(item => {
						/* item.id = parseInt(Math.random() * 10000); */
						tabItem.newsList.push(item);
					})
					//下拉刷新 关闭刷新动画
					if (type === 'refresh') {
						this.$refs.mixPulldownRefresh && this.$refs.mixPulldownRefresh.endPulldownRefresh();
						// #ifdef APP-PLUS
						tabItem.refreshing = false;
						// #endif
						tabItem.loadMoreStatus = 0;
					}
					//上滑加载 处理状态
					if (type === 'add') {
						tabItem.loadMoreStatus = tabItem.newsList.length > 40 ? 2 : 0;
						this.page_index++
					}
				}, 600)
			},
			
			//下拉刷新
			onPulldownReresh() {
				this.loadNewsList('refresh');
			},
			//上滑加载
			loadMore() {
				this.loadNewsList('add');
			},
			//设置scroll-view是否允许滚动，在小程序里下拉刷新时避免列表可以滑动
			setEnableScroll(enable) {
				if (this.enableScroll !== enable) {
					this.enableScroll = enable;
				}
			},

			//tab切换
			async changeTab(e, channelId) {
				this.listChannel = false
				if (scrollTimer) {
					//多次切换只执行最后一次
					clearTimeout(scrollTimer);
					scrollTimer = false;
				}
				let index = e;
				//e=number为点击切换，e=object为swiper滑动切换
				if (typeof e === 'object') {
					index = e.detail.current
				}
				if (typeof tabBar !== 'object') {
					tabBar = await this.getElSize("nav-bar")
				}
				//计算宽度相关
				let tabBarScrollLeft = tabBar.scrollLeft;
				let width = 0;
				let nowWidth = 0;
				//获取可滑动总宽度
				for (let i = 0; i <= index; i++) {
					let result = await this.getElSize('tab' + i);
					width += result.width;
					if (i === index) {
						nowWidth = result.width;
					}
				}
				if (typeof e === 'number') {
					//点击切换时先切换再滚动tabbar，避免同时切换视觉错位
					this.tabCurrentIndex = index;
				}
				//延迟300ms,等待swiper动画结束再修改tabbar
				scrollTimer = setTimeout(() => {
					if (width - nowWidth / 2 > windowWidth / 2) {
						//如果当前项越过中心点，将其放在屏幕中心
						this.scrollLeft = width - nowWidth / 2 - windowWidth / 2;
					} else {
						this.scrollLeft = 0;
					}
					if (typeof e === 'object') {
						this.tabCurrentIndex = index;
					}
					this.tabCurrentIndex = index;


					//第一次切换tab，动画结束后需要加载数据
					let tabItem = this.tabBars[this.tabCurrentIndex];
					if (this.tabCurrentIndex !== 0 && tabItem.loaded !== true) {
						this.loadNewsList('add');
						tabItem.loaded = true;
					}
				}, 10)

			},
			//获得元素的size
			getElSize(id) {
				return new Promise((res, rej) => {
					let el = uni.createSelectorQuery().select('#' + id);
					el.fields({
						size: true,
						scrollOffset: true,
						rect: true
					}, (data) => {
						res(data);
					}).exec();
				});
			},
		}
	}
</script>

<style lang='scss' scoped>
	page,
	.content {
		background-color: #f8f8f8;
		height: 100%;
		overflow: hidden;
	}

	/* 频道列表 */
	.channelTxt {
		width: 100%;
		padding: 100rpx 15rpx 10rpx 15rpx;

		view {
			color: #080808;
			font-size: 50rpx;
			position: relative;

			text {
				position: absolute;
				top: 26rpx;
				left: 228rpx;
				font-size: 25rpx;
				color: #cbcbcb;
			}

			.edit {
				position: absolute;
				top: 20rpx;
				right: 50rpx;
				color: #ed4141;
				font-size: 30rpx;
			}
		}
	}

	.channelTag {
		padding: 15rpx;
		display: inline-block;

		.tag-info {
			display: inline-block;
			float: left;
			margin: 15rpx 0 15rpx 30rpx;
		}
	}

	/* 顶部tabbar */
	.tab-frame {
		position: relative;

		.nab-icon {
			background-image: linear-gradient(90deg, rgba(255, 255, 255, 0.7), #ffffff);
			width: 13%;
			height: 90rpx;
			position: absolute;
			right: 0rpx;
			top: 0rpx;
			z-index: 10;

			.icon {
				margin: 17rpx;
				margin-right: 0rpx;
			}
		}
	}

	.nav-bar {
		position: relative;
		z-index: 10;
		height: 90upx;
		white-space: nowrap;
		width: 90%;
		box-shadow: 0 2upx 8upx rgba(0, 0, 0, .06);
		background-color: #fff;

		.nav-item {
			display: inline-block;
			/* width: 120upx; */
			height: 90upx;
			padding: 0 20rpx;
			text-align: center;
			line-height: 90upx;
			font-size: 30upx;
			color: #303133;
			position: relative;

			&:after {
				content: '';
				width: 0;
				height: 0;
				border-bottom: 4upx solid #ed4141;
				position: absolute;
				left: 50%;
				bottom: 0;
				transform: translateX(-50%);
				transition: .3s;
			}
		}

		.current {
			color: #ed4141;

			&:after {
				width: 50%;
			}
		}
	}

	.swiper-box {
		height: 100%;
	}

	.panel-scroll-box {
		height: 100%;

		.panel-item {
			background: #fff;
			padding: 30px 0;
			border-bottom: 2px solid #000;
		}
	}

	/**
	 * 直播列表 
	 */
	.video-frame {
		padding: 20rpx;
		background-color: #fff;
		height: 600rpx;
		margin-bottom: 10rpx;
		border-radius: 20rpx;

		.frame-trxt {
			font-size: 35rpx;
			padding-bottom: 10rpx;

			text {
				font-weight: 800;
				padding-right: 30rpx;
			}
		}

		.forame-image {
			position: relative;



			image {
				border-radius: 10rpx;
				width: 100%;
				height: 400rpx;
			}

			.frame-watch {
				position: absolute;
				top: 20rpx;
				left: 20rpx;
				width: 230rpx;
				height: 60rpx;
				border-radius: 15rpx;
				font-size: 25rpx;
				line-height: 60rpx;
				color: #fff;
				background-color: rgba($color: #000000, $alpha: 0.4);

				view {
					border-radius: 15rpx;
					display: inline-block;
					background-color: #ed4141;
					padding: 0 20rpx;
				}

				text {
					margin-left: 20rpx;
				}
			}
		}


		.video-content {
			width: 100%;
			margin-bottom: 30rpx;
			display: flex;
			font-size: 26rpx;
			color: #909399;
			justify-content: center; //子元素水平居中
			align-items: center; //子元素垂直居中

			.frame_img {
				flex: 1;
				width: 90rpx;
				height: 90rpx;
				border-radius: 50px;

				image {
					border-radius: 50px;
					width: 90rpx;
					height: 90rpx;
				}
			}

			.frame_tltle {
				margin-left: 30rpx;
				flex: 5;

				text {
					margin-right: 16rpx;
				}

				view {
					font-weight: 600;
					font-size: 30rpx;
					color: #000000;
				}
			}

			button {
				flex: 1;
				height: 60rpx;
				line-height: 45rpx;
				font-size: 30rpx;
				background-color: #ed4141;
				color: #fff;
			}
		}
	}
</style>
